package com.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.AnnouncesDao;
import com.model.Announces;

@WebServlet("/DowSer")
public class DowSer extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String filePath;

    public DowSer() {
        super();
   
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   String id = request.getParameter("id");
			request.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream");
			response.setHeader("content-disposition", "attachment;filename=");
		    System.out.println(id);
		  
		   
		    Announces ann = new Announces();
		    AnnouncesDao annD = new AnnouncesDao();
		    ann.setAnnouncesID(Integer.valueOf(id));
		    List<Announces> list = annD.byIDonSomething(ann);
		    for (Announces a : list) {
			      filePath =  a.getFile();
			}
		    //获取file路径
		    
		    String filename = new String( filePath.substring(filePath.lastIndexOf("/")+1).getBytes("UTF-8"), "ISO8859-1");
		    //将文件名称之截取出来（从倒数/开始的后一位字符取到，并将其转换成流类型，传输头类型改为iso）
			response.setContentType("application/octet-stream");
			response.setHeader("content-disposition", "attachment;filename="+filename);
 		    FileInputStream is = new FileInputStream(filePath);
 		    int len = 0 ;
 		    byte[]   by = new  byte[1024];
 		    while((len=is.read())!=-1){
 		    	response.getOutputStream().write(by);
 		    }
 		    
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}
